package org.example.bulletin.service.Impl;

import org.example.bulletin.entity.dto.Bulletindto;
import org.example.bulletin.entity.vo.Bulletinvo;
import org.example.bulletin.repository.BulletinRepository;
import org.example.bulletin.service.BulletinService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.List;

@Service
public class BulletinServiceImpl implements BulletinService {
    private final BulletinRepository bulletinRepository;

    public BulletinServiceImpl(BulletinRepository bulletinRepository) {
        this.bulletinRepository = bulletinRepository;
    }

    @Override
    @Cacheable(value = "CommentCache", sync = true)
    public PageInfo<Bulletinvo> getList(int pageNumber, int pageSize) {
        PageHelper.startPage(pageNumber, pageSize);
        List<Bulletinvo> l = bulletinRepository.getList();
        return new PageInfo<>(l);
    }
    @Override
    @Cacheable(value = "CommentCache", sync = true)
    public List<Bulletinvo> getTopList() {
        return bulletinRepository.getTopList();
    }
    @Override
    @Transactional
    @CacheEvict(value = "CommentCache", allEntries = true, beforeInvocation = true)
    public void addBulletin(Bulletindto bulletindto) {
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
// 设置纳秒部分，保留最多6位微秒
        timestamp.setNanos(timestamp.getNanos() / 1000 * 1000);
        bulletindto.setCreateTime(timestamp.toString());
        bulletinRepository.addBulletinContent(bulletindto);
        bulletinRepository.addBulletin(bulletindto);
    }
    @Override
    @Transactional
    @CacheEvict(value = "CommentCache", allEntries = true, beforeInvocation = true)
    public void updateBulletin(Bulletindto bulletindto) {
        bulletinRepository.updateBulletin(bulletindto);
        bulletinRepository.updateBulletinContent(bulletindto);
    }
    @Override
    @CacheEvict(value = "CommentCache", allEntries = true, beforeInvocation = true)
    public void deleteBulletin(Bulletindto bulletindto) {
        bulletinRepository.deleteBulletin(bulletindto);
        bulletinRepository.deleteBulletinContent(bulletindto);
    }
    @Override
    @Cacheable(value = "CommentCache", sync = true)
    public Bulletinvo getBulletin(Integer id) {
        return bulletinRepository.getBulletin(id);
    }

    @Override
    public List bulletinl() {
        return bulletinRepository.getList();
    }
}
